﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Test_QianBZ.Models;
using Test_QianBZ.DataAccess;
namespace Test_QianBZ.Repository
{
    public class EatLogRepository
    {
        public List<EatLogModel> GetLog(int personId)
        {
            var db = new eatContext();
            var eatlog = db.TbEatlog
                .Where(s => s.PersonId == personId || personId == 0)
                .Select(s => new EatLogModel {
                    EatTime = s.EatTime,
                    FoodId = s.FoodId,
                    LogId =s.LogId,
                    PersonId = s.PersonId,
                    EatCount = s.EatCount
                })
                .ToList();
            return eatlog;
        }

        public int AddLog(EatLogModel food)
        {
            var db = new eatContext();
            var tbeatlog = new TbEatlog
            {
                EatCount = food.EatCount,
                EatTime = food.EatTime,
                FoodId = food.FoodId,
                PersonId = food.PersonId
            };
            db.TbEatlog.Add(tbeatlog);
            return (db.SaveChanges());
        }

        public List<EatDetailModel> GetLogWithName(int personId)
        {
            var db = new eatContext();
            var eatlog =(from l in db.TbEatlog
                         join p in db.TbPerson on l.PersonId equals p.PersonId into t
                         from d in t
                         join f in db.TbMenu on l.FoodId equals f.FoodId into y
                         from x in y
                         where l.PersonId == personId || personId ==0
                         select new EatDetailModel {
                             EatCount = l.EatCount,
                             EatTime = l.EatTime,
                             FoodId = l.FoodId,
                             FoodName = x.FoodName,
                             LogId = l.LogId,
                             PersonId = l.PersonId,
                             PersonName = d.PersonName
                         }
                ).ToList();
            return eatlog;
        }

        public int DelEatLog(int LogId)
        {
            var db = new eatContext();
            var row = db.TbEatlog.Where(s => s.LogId == LogId).FirstOrDefault();
            if (row != null)
            {
                db.TbEatlog.Remove(row);
                return db.SaveChanges();
            }
            else
            {
                return 0;
            }
        }
    }
}
